package com.imachen.ymcc.mq.consumer;

import com.imachen.ymcc.domain.PayOrder;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import com.imachen.ymcc.service.IPayOrderService;
import com.imachen.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "tx-pay-delay-cancel-consumer-group",
        topic = "tx-order-delay-topic",
        selectorExpression = "tx-order-delay-tag",
        messageModel = MessageModel.BROADCASTING
)
public class PayDelayCancelConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;


    /**
     * 延迟消息取消订单 消费者。取消支付订单
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取消息参数，业务校验
        log.info("延迟消息支付消费开始");
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotEmpty(orderNo, GlobalExceptionCode.ERROR);
        PayOrder payOrder = payOrderService.selectPayByOrderNo(orderNo);
        if (payOrder == null) {
            return;
        }

        if (payOrder.getPayStatus().equals(PayOrder.WAIT_PAY_STATUS)) {
            // 如果是待支付状态 就取消订单
            payOrderService.cancelPayOrder(orderNo,payOrder);
        }

        log.info("延迟消息支付消费结束");
    }
}
